<?php
/**
 * Mechanism
 * 
 * LICENSE
 * 
 * This file is private intellectual property of the author. 
 * All rights reserved. Copying and illegal using is punishable by law.
 * 
 * @copyright Copyright (c) 2011 BreatheInMyVoid ( BreatheInMyVoid@gmail.com )
 */

namespace Mechanism\Response {
	class Http extends Response {
		protected $headers = array( );
		protected $content = array( );
		protected $code = 200;
		protected $is_headers_sent = false;


		public function __construct( $content = '' ) {
			if ( $content ) {
				$this->content['default'] = $content;
			}
		}

		public function get_headers( ) {
			return $this->headers;
		}

		public function get_content( ) {
			return $this->content;
		}

		public function get_code( ) {
			return $this->code;
		}

		public function set_headers( array $headers ) {
			$this->headers = $headers;
		}

		public function set_content( array $content ) {
			$this->content = $content;
		}

		public function set_code( $code ) {
			$this->code = $code;
		}

		public function append_header( $header, $replace = true, $code = null ) {
			array_push( $this->headers, array( 'header'	 => $header,
											   'replace' => $replace,
											   'code'    => $code ) );
		}

		public function append_content( $name, $value ) {
			( array ) $this->content += array( $name => $value );
		}

		public function prepend_header( $header, $replace = true, $code = null ) {
			$new = array( array( 'header'  => $header,
								 'replace' => $replace,
								 'code'    => $code ) );

			foreach( $this->headers as $value ) {
				array_push( $new, $value );
			}

			$this->headers = $new;
		}

		public function prepend_content( $name, $value ) {
			$this->content = array( $name => $value ) + $this->content;
		}

		public function clear_headers( ) {
			$this->headers = array( );
		}

		public function clear_content( $name = null ) {
			if ( null !== $name && array_key_exists( $name, $this->content ) ) {
				unset( $this->content[$name] );	
			} else {
				$this->content = array( );
			}
		}

		public function send_headers( ) {
			if ( headers_sent( ) ) {
				throw new Exception( 'Cannot send response. Headers or 
									  content have been sent manually' );
			}

			if ( false === $this->is_headers_sent ) {
				/* Send code */
				header( 'HTTP/1.1 ' . $this->code );

				foreach( $this->headers as $header ) {
					header( $header['header'], $header['replace'], $header['code'] );
				}

				$this->is_headers_sent = true;
			}
		}
		
		public function send_content( ) {
			echo implode( '', $this->content );
		}
		
		/**
		 *
		 * Note that shutdown functions and object destructors
		 * will be called after exit( )
		 *
		 */
		public function send( ) {
			$this->send_headers( );
			$this->send_content( );
			/* Stop all works when response is already sent */
			exit( 0 );
		}	
	}
}
